import 'package:flutter/material.dart';
import '../../core/base/base_view_model.dart';
import '../../core/http/api_response.dart';
import '../../core/http/http_client.dart';
import 'user_model.dart';

class UserListViewModel extends BaseViewModel {
  final _httpClient = HttpClient();
  List<UserModel> users = [];
  List<UserModel> filteredUsers = [];
  String searchKeyword = '';

  // 分页相关
  int currentPage = 1;
  int pageSize = 10;
  int totalItems = 0;

  bool get hasNextPage => currentPage * pageSize < totalItems;

  // 排序相关
  String sortField = 'created_at';
  String sortOrder = 'desc';

  Future<void> fetchUsers({int page = 1}) async {
    try {
      setBusy(true);
      final response = await _httpClient.get<PaginationData<UserModel>>(
        '/admin/list',
        params: {
          'page': page,
          'page_size': pageSize,
          'sort_field': sortField,
          'sort_order': sortOrder,
        },
        fromJson: (json) => PaginationData.fromJson(
          json as Map<String, dynamic>,
          (item) => UserModel.fromJson(item),
        ),
      );

      if (response.isSuccess) {
        final paginationData = response.data!;
        users = paginationData.list;
        totalItems = paginationData.total;
        currentPage = page;
        _filterUsers();
        setState(users.isEmpty ? ViewState.empty : ViewState.idle);
      } else {
        setError(response.message);
      }
    } catch (e) {
      setError(e.toString());
    } finally {
      setBusy(false);
    }
  }

  Future<void> createUser(Map<String, dynamic> userData) async {
    try {
      setBusy(true);
      final response = await _httpClient.post<void>('/admin/register', data: userData);

      if (response.isSuccess) {
        await fetchUsers(page: currentPage);
      } else {
        setError(response.message);
      }
    } catch (e) {
      setError(e.toString());
    } finally {
      setBusy(false);
    }
  }

  Future<void> updateUser(int id, Map<String, dynamic> userData) async {
    try {
      setBusy(true);

      // 处理roles数据
      if (userData.containsKey('roles')) {
        // 确保roles是一个包含完整role对象的数组
        List<dynamic> roles = userData['roles'];
        userData['roles'] = roles.map((role) {
          if (role is Map<String, dynamic>) {
            return role;
          } else if (role is int) {
            // 如果role是ID，转换为完整的role对象
            return {
              'id': role,
              'name': '', // 这些字段会在后端被忽略
              'code': ''
            };
          }
          return role;
        }).toList();
      }

      final response = await _httpClient.put<void>('/admin/update/$id', data: userData);

      if (response.isSuccess) {
        await fetchUsers(page: currentPage);
      } else {
        setError(response.message);
      }
    } catch (e) {
      setError(e.toString());
    } finally {
      setBusy(false);
    }
  }

  Future<void> deleteUser(int id) async {
    try {
      setBusy(true);
      final response = await _httpClient.delete<void>('/admin/$id');

      if (response.isSuccess) {
        await fetchUsers(page: currentPage);
      } else {
        setError(response.message);
      }
    } catch (e) {
      setError(e.toString());
    } finally {
      setBusy(false);
    }
  }

  void searchUsers(String keyword) {
    searchKeyword = keyword;
    _filterUsers();
    notifyListeners();
  }

  void sortUsers(String sort) {
    final parts = sort.split('_');
    if (parts.length == 2) {
      sortField = parts[0];
      sortOrder = parts[1];
      fetchUsers();
    }
  }

  void nextPage() {
    if (hasNextPage) {
      currentPage++;
      fetchUsers();
    }
  }

  void previousPage() {
    if (currentPage > 1) {
      currentPage--;
      fetchUsers();
    }
  }

  void _filterUsers() {
    if (searchKeyword.isEmpty) {
      filteredUsers = List.from(users);
    } else {
      filteredUsers = users
          .where((user) =>
              user.username.toLowerCase().contains(searchKeyword.toLowerCase()) ||
              user.email.toLowerCase().contains(searchKeyword.toLowerCase()) ||
              user.nickname.toLowerCase().contains(searchKeyword.toLowerCase()) ||
              (user.phone?.toLowerCase().contains(searchKeyword.toLowerCase()) ?? false))
          .toList();
    }
  }
}
